package com.od.controller;

import java.util.ArrayList;
import java.util.List;

import com.od.utils.CityJson;
import com.od.utils.ProvinceJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.od.entity.City;
import com.od.service.CityService;
import com.od.utils.ProvinceCity;

@Controller
@RequestMapping("city")
@CrossOrigin
public class CityController {
    @Autowired
    private CityService cityService;

    @RequestMapping("allCities")
    @ResponseBody
    public List<City> allCities() {
        return cityService.getAllCities();
    }

    @RequestMapping("allProvinceCity")
    @ResponseBody
    public List<ProvinceJson> allProvinceCity() {
        List<ProvinceJson> provinceJsons = new ArrayList<>();
        List<ProvinceCity> provinceCities = cityService.getProvinceCity();
        for(ProvinceCity provinceCity : provinceCities) {
            ProvinceJson provinceJson = new ProvinceJson();
            provinceJson.setValue(provinceCity.getProvinceId());
            provinceJson.setLabel(provinceCity.getProvinceName());
            List<CityJson> cityJsons = new ArrayList<>();
            for(City city : provinceCity.getCities()) {
                CityJson cityJson = new CityJson(city.getCityId(), city.getCityName());
                cityJsons.add(cityJson);
            }
            provinceJson.setChildren(cityJsons);
            provinceJsons.add(provinceJson);
        }
        return provinceJsons;
    }

    @RequestMapping("getCityNameById")
    @ResponseBody
    public String getCityNameById(int cityId) {
        return cityService.getCityNameById(cityId);
    }

}
